package com.sample.nfctest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Date;

import android.app.Activity;
import android.bluetooth.BluetoothServerSocket;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.widget.EditText;
import android.widget.Toast;

public class NFCTestActivity extends Activity implements CreateNdefMessageCallback {

	EditText input;
	EditText output;
	NdefMessage msgs[];
	NdefRecord msg;
	NfcAdapter nfcAdapter;
	boolean somethingHappened = false; 
	double initialTime;
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//Toast.makeText(this, "HELLO!?!?!", Toast.LENGTH_LONG).show();
		input = (EditText) findViewById(R.id.editText1);
		output = (EditText) findViewById(R.id.editText2);
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (nfcAdapter == null)
		{
			Toast.makeText(this, "No NFC.  Sucks to suck.", Toast.LENGTH_LONG).show();
			return;
		}
        nfcAdapter.setNdefPushMessageCallback(this, this);
		//initialTime =  new Date(0).getTime();
		//while(!somethingHappened)
		//{
			//if(30000 < new Date(0).getTime() - initialTime)
				//somethingHappened = true;
		//	nfc();
		//}
	}
	/*public void nfc()
	{
		msg = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, "text/plain".getBytes(), 
	    		new byte[0], input.getText().toString().getBytes());
	    input.setText("");
	    NdefRecord send[] = {msg};
	    try{
	    	nfcAdapter.setNdefPushMessage(new NdefMessage(send), this);
	    	somethingHappened = true;
	    }catch(Exception e){Toast.makeText(this, "Android Beam Failed", Toast.LENGTH_LONG);}
	    
	    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
	    	Intent intent = getIntent();
	        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
	        if (rawMsgs != null) 
	        {
	        	somethingHappened = true;
	            msgs = new NdefMessage[rawMsgs.length];
	            for (int i = 0; i < rawMsgs.length; i++) 
	            {
	                msgs[i] = (NdefMessage) rawMsgs[i];
	                output.append(msgs[i].toString());
	            }
	        }	        
	    }
	    else
	    {
	    	Toast.makeText(this, "No other NFC device detected.", Toast.LENGTH_LONG).show();
	    }
	}*/
	public void onResume() 
	{
	    super.onResume();
        if (nfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
        if (nfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
        if (nfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
	}
	public NdefMessage createNdefMessage(NfcEvent event) {
        String text = input.getText().toString();
        File file = new File("/storage/sdcard0/Music/Bastion/Supergiant Games - Bastion Original Soundtrack - 03 In Case of Trouble.mp3");

        byte[] b = new byte[(int) file.length()];
        try {
        	FileInputStream fileInputStream = new FileInputStream(file);
        	fileInputStream.read(b);
        }catch(Exception e){}
        NdefMessage msg = new NdefMessage(new NdefRecord[] { 
        		createMimeRecord("application/com.sample.nfctest", text.getBytes())});
        return msg;
	}
    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }
    void processIntent(Intent intent) 
    {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                nfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        output.setText(new String(msg.getRecords()[0].getPayload()));
    }
    public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
        NdefRecord mimeRecord = new NdefRecord(
                NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
        return mimeRecord;
    }
}